#include <QMap>
#include <QString>
#include "track_id_data_integrated.h"

#include "constant_variables.h"

Track_id_data_integrated::Track_id_data_integrated(QString track_data, QObject *parent) :
    QObject(parent),
    track_data_map_(new QMap<QString, QString>()),
    track_data_(track_data)
{
    setup_track_data(track_data_);
}

Track_id_data_integrated::~Track_id_data_integrated()
{
    if (nullptr != track_data_map_) {
        delete track_data_map_;
        track_data_map_ = nullptr;
    }
}

Track_id_data_integrated::Track_id_data_integrated(const Track_id_data_integrated &rvalue)
{
    if (this != &rvalue) {
        if (nullptr != track_data_map_) {
            delete track_data_map_;
        }

        track_data_map_ = new QMap<QString, QString>();

        QMap<QString, QString>::iterator iterator = rvalue.track_data_map_->begin();
        QMap<QString, QString>::ConstIterator const_iterator(rvalue.track_data_map_->end());

        // 遍历参数rvalue，将K/V保存到容器
        while (const_iterator != iterator) {
            track_data_map_->insert(iterator.key(), iterator.value());
            ++iterator;
        }
    }
}

Track_id_data_integrated& Track_id_data_integrated::operator =(const Track_id_data_integrated& rvalue)
{
    if (this != &rvalue) {
        if (nullptr != track_data_map_) {
            delete track_data_map_;
        }

        track_data_map_ = new QMap<QString, QString>();

        QMap<QString, QString>::iterator iterator = rvalue.track_data_map_->begin();
        QMap<QString, QString>::ConstIterator const_iterator(rvalue.track_data_map_->end());

        while (const_iterator != iterator) {
            track_data_map_->insert(iterator.key(), iterator.value());
            ++iterator;
        }
    }

    return *this;
}

QMap<QString, QString> *Track_id_data_integrated::get_track_data()
{
    return track_data_map_;
}

void Track_id_data_integrated::setup_track_data(QString content)
{
    // 数据时间hh:mm:ss
    QString data_time(content.mid(0, 8));
    track_data_map_->insert(TIME.trimmed(), data_time.trimmed());

    QStringList list = content.mid(11).split(",");
    QStringList key_value_group;

    QStringList::Iterator iter;

    // 将数据进行处理，保存到track_data_map_中
    for (iter = list.begin(); list.end() != iter; ++iter) {
        key_value_group = iter->split("=");

        if (2 == key_value_group.count()) {
            if (key_value_group[1].isEmpty()) {
                key_value_group[1] = "None";
            }

            // 将key/value保存到QMap中，去除数据的空格。将航班号的方括号去除
            track_data_map_->insert(key_value_group[0].trimmed(),
                    key_value_group[1].trimmed().replace("[", "").replace("]", ""));
        }
    }
}
